import React, { createContext, useContext, useState } from 'react';
import { PlayCircle, PauseCircle, CheckCircle, AlertCircle, Clock, Users } from 'lucide-react';

// 工作流上下文
const WorkflowContext = createContext();

// 工作流状态定义
const WORKFLOW_STATUS = {
  draft: { label: '草稿', color: 'gray', icon: Clock },
  active: { label: '执行中', color: 'blue', icon: PlayCircle },
  paused: { label: '暂停', color: 'yellow', icon: PauseCircle },
  completed: { label: '已完成', color: 'green', icon: CheckCircle },
  cancelled: { label: '已取消', color: 'red', icon: AlertCircle }
};

// 预定义的跨模块业务流程模板
const WORKFLOW_TEMPLATES = {
  'annual-esg-report': {
    name: '年度ESG报告',
    description: '整合所有模块数据生成年度ESG综合报告',
    modules: ['carbon', 'compliance', 'supply-chain', 'reporting'],
    estimatedDuration: 45, // 天
    steps: [
      {
        id: 'data-collection',
        name: '数据收集',
        description: '收集各模块年度数据',
        module: 'carbon',
        assignee: 'carbon-manager',
        duration: 7,
        dependencies: []
      },
      {
        id: 'compliance-review',
        name: '合规审核',
        description: '确保所有数据符合法规要求',
        module: 'compliance',
        assignee: 'compliance-officer',
        duration: 10,
        dependencies: ['data-collection']
      },
      {
        id: 'supplier-assessment',
        name: '供应链评估',
        description: '完成供应商ESG表现评估',
        module: 'supply-chain',
        assignee: 'supply-chain-manager',
        duration: 14,
        dependencies: ['data-collection']
      },
      {
        id: 'report-generation',
        name: '报告生成',
        description: '生成最终ESG报告',
        module: 'reporting',
        assignee: 'analyst',
        duration: 10,
        dependencies: ['compliance-review', 'supplier-assessment']
      },
      {
        id: 'final-review',
        name: '最终审核',
        description: 'ESG总监最终审核',
        module: 'reporting',
        assignee: 'esg-director',
        duration: 4,
        dependencies: ['report-generation']
      }
    ]
  },
  'carbon-reduction-plan': {
    name: '碳减排行动计划',
    description: '制定和执行企业碳减排策略',
    modules: ['carbon', 'supply-chain', 'compliance'],
    estimatedDuration: 60,
    steps: [
      {
        id: 'baseline-assessment',
        name: '基线评估',
        description: '评估当前碳排放基线',
        module: 'carbon',
        assignee: 'carbon-manager',
        duration: 14,
        dependencies: []
      },
      {
        id: 'target-setting',
        name: '目标设定',
        description: '设定减排目标和时间表',
        module: 'carbon',
        assignee: 'esg-director',
        duration: 7,
        dependencies: ['baseline-assessment']
      },
      {
        id: 'supplier-engagement',
        name: '供应商参与',
        description: '制定供应商减排要求',
        module: 'supply-chain',
        assignee: 'supply-chain-manager',
        duration: 21,
        dependencies: ['target-setting']
      },
      {
        id: 'compliance-check',
        name: '合规检查',
        description: '确保减排计划符合法规',
        module: 'compliance',
        assignee: 'compliance-officer',
        duration: 10,
        dependencies: ['supplier-engagement']
      },
      {
        id: 'implementation',
        name: '计划实施',
        description: '执行减排措施',
        module: 'carbon',
        assignee: 'carbon-manager',
        duration: 30,
        dependencies: ['compliance-check']
      }
    ]
  },
  'product-launch-esg': {
    name: '产品ESG整合发布',
    description: '新产品功能的跨模块协调发布流程',
    modules: ['workbench', 'carbon', 'compliance', 'reporting'],
    estimatedDuration: 30,
    steps: [
      {
        id: 'requirement-analysis',
        name: '需求分析',
        description: '分析产品功能需求',
        module: 'workbench',
        assignee: 'product-manager',
        duration: 5,
        dependencies: []
      },
      {
        id: 'esg-integration',
        name: 'ESG功能整合',
        description: '整合ESG相关功能',
        module: 'carbon',
        assignee: 'carbon-manager',
        duration: 10,
        dependencies: ['requirement-analysis']
      },
      {
        id: 'compliance-validation',
        name: '合规验证',
        description: '验证功能合规性',
        module: 'compliance',
        assignee: 'compliance-officer',
        duration: 7,
        dependencies: ['esg-integration']
      },
      {
        id: 'reporting-setup',
        name: '报告配置',
        description: '配置相关报告功能',
        module: 'reporting',
        assignee: 'analyst',
        duration: 5,
        dependencies: ['compliance-validation']
      },
      {
        id: 'launch-coordination',
        name: '发布协调',
        description: '协调各模块同步发布',
        module: 'workbench',
        assignee: 'product-manager',
        duration: 3,
        dependencies: ['reporting-setup']
      }
    ]
  }
};

// 工作流提供者
export const WorkflowProvider = ({ children }) => {
  const [workflows, setWorkflows] = useState([
    {
      id: 'wf-001',
      templateId: 'annual-esg-report',
      name: '2024年度ESG报告',
      status: 'active',
      progress: 65,
      currentStep: 'compliance-review',
      startDate: '2024-02-01',
      dueDate: '2024-03-31',
      owner: 'esg-director',
      participants: ['carbon-manager', 'compliance-officer', 'supply-chain-manager', 'analyst'],
      priority: 'high'
    },
    {
      id: 'wf-002',
      templateId: 'carbon-reduction-plan',
      name: '2024-2025碳减排计划',
      status: 'active',
      progress: 35,
      currentStep: 'supplier-engagement',
      startDate: '2024-01-15',
      dueDate: '2024-04-15',
      owner: 'carbon-manager',
      participants: ['esg-director', 'supply-chain-manager', 'compliance-officer'],
      priority: 'high'
    },
    {
      id: 'wf-003',
      templateId: 'product-launch-esg',
      name: '供应链模块V2.0发布',
      status: 'draft',
      progress: 15,
      currentStep: 'requirement-analysis',
      startDate: '2024-03-01',
      dueDate: '2024-04-01',
      owner: 'product-manager',
      participants: ['carbon-manager', 'compliance-officer', 'analyst'],
      priority: 'medium'
    }
  ]);

  // 创建新工作流
  const createWorkflow = (templateId, customData = {}) => {
    const template = WORKFLOW_TEMPLATES[templateId];
    if (!template) return null;

    const newWorkflow = {
      id: `wf-${Date.now()}`,
      templateId,
      name: customData.name || template.name,
      status: 'draft',
      progress: 0,
      currentStep: template.steps[0]?.id,
      startDate: new Date().toISOString().split('T')[0],
      dueDate: new Date(Date.now() + template.estimatedDuration * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
      owner: customData.owner,
      participants: customData.participants || [],
      priority: customData.priority || 'medium',
      ...customData
    };

    setWorkflows(prev => [...prev, newWorkflow]);
    return newWorkflow;
  };

  // 更新工作流状态
  const updateWorkflowStatus = (workflowId, status) => {
    setWorkflows(prev => prev.map(wf => 
      wf.id === workflowId ? { ...wf, status } : wf
    ));
  };

  // 推进工作流到下一步
  const advanceWorkflow = (workflowId) => {
    const workflow = workflows.find(wf => wf.id === workflowId);
    if (!workflow) return;

    const template = WORKFLOW_TEMPLATES[workflow.templateId];
    const currentStepIndex = template.steps.findIndex(step => step.id === workflow.currentStep);
    const nextStep = template.steps[currentStepIndex + 1];

    if (nextStep) {
      const newProgress = Math.round(((currentStepIndex + 1) / template.steps.length) * 100);
      setWorkflows(prev => prev.map(wf =>
        wf.id === workflowId
          ? { ...wf, currentStep: nextStep.id, progress: newProgress }
          : wf
      ));
    } else {
      // 工作流完成
      setWorkflows(prev => prev.map(wf =>
        wf.id === workflowId
          ? { ...wf, status: 'completed', progress: 100 }
          : wf
      ));
    }
  };

  // 获取工作流详情
  const getWorkflowDetails = (workflowId) => {
    const workflow = workflows.find(wf => wf.id === workflowId);
    if (!workflow) return null;

    const template = WORKFLOW_TEMPLATES[workflow.templateId];
    return {
      ...workflow,
      template,
      currentStepDetails: template.steps.find(step => step.id === workflow.currentStep)
    };
  };

  // 获取用户相关的工作流
  const getUserWorkflows = (userId) => {
    return workflows.filter(wf => 
      wf.owner === userId || wf.participants.includes(userId)
    );
  };

  // 获取模块相关的工作流
  const getModuleWorkflows = (moduleId) => {
    return workflows.filter(wf => {
      const template = WORKFLOW_TEMPLATES[wf.templateId];
      return template && template.modules.includes(moduleId);
    });
  };

  // 获取待处理任务
  const getPendingTasks = (userId) => {
    const tasks = [];
    
    workflows.forEach(workflow => {
      if (workflow.status === 'active') {
        const template = WORKFLOW_TEMPLATES[workflow.templateId];
        const currentStep = template.steps.find(step => step.id === workflow.currentStep);
        
        if (currentStep && currentStep.assignee === userId) {
          tasks.push({
            id: `${workflow.id}-${currentStep.id}`,
            workflowId: workflow.id,
            workflowName: workflow.name,
            stepName: currentStep.name,
            description: currentStep.description,
            module: currentStep.module,
            priority: workflow.priority,
            dueDate: workflow.dueDate
          });
        }
      }
    });
    
    return tasks;
  };

  const value = {
    workflows,
    templates: WORKFLOW_TEMPLATES,
    createWorkflow,
    updateWorkflowStatus,
    advanceWorkflow,
    getWorkflowDetails,
    getUserWorkflows,
    getModuleWorkflows,
    getPendingTasks
  };

  return (
    <WorkflowContext.Provider value={value}>
      {children}
    </WorkflowContext.Provider>
  );
};

// 使用工作流的Hook
export const useWorkflow = () => {
  const context = useContext(WorkflowContext);
  if (!context) {
    throw new Error('useWorkflow must be used within a WorkflowProvider');
  }
  return context;
};

// 工作流状态标签组件
export const WorkflowStatusBadge = ({ status, className = '' }) => {
  const config = WORKFLOW_STATUS[status];
  if (!config) return null;

  const colorClasses = {
    gray: 'bg-gray-100 text-gray-800',
    blue: 'bg-blue-100 text-blue-800',
    yellow: 'bg-yellow-100 text-yellow-800',
    green: 'bg-green-100 text-green-800',
    red: 'bg-red-100 text-red-800'
  };

  const Icon = config.icon;

  return (
    <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${colorClasses[config.color]} ${className}`}>
      <Icon className="h-3 w-3 mr-1" />
      {config.label}
    </span>
  );
};

// 工作流进度条组件
export const WorkflowProgress = ({ progress, className = '' }) => {
  return (
    <div className={`w-full ${className}`}>
      <div className="flex items-center justify-between mb-1">
        <span className="text-sm font-medium text-gray-700">进度</span>
        <span className="text-sm text-gray-500">{progress}%</span>
      </div>
      <div className="w-full bg-gray-200 rounded-full h-2">
        <div 
          className="bg-blue-600 h-2 rounded-full transition-all duration-500"
          style={{ width: `${progress}%` }}
        />
      </div>
    </div>
  );
};

// 工作流参与者组件
export const WorkflowParticipants = ({ participants, maxDisplay = 4, className = '' }) => {
  const displayParticipants = participants.slice(0, maxDisplay);
  const remaining = participants.length - maxDisplay;

  return (
    <div className={`flex items-center ${className}`}>
      <Users className="h-4 w-4 text-gray-500 mr-2" />
      <div className="flex -space-x-1">
        {displayParticipants.map((participant, index) => (
          <div
            key={participant}
            className="w-6 h-6 bg-gray-300 rounded-full border-2 border-white flex items-center justify-center"
            title={participant}
          >
            <span className="text-xs font-medium text-gray-600">
              {participant.charAt(0).toUpperCase()}
            </span>
          </div>
        ))}
        {remaining > 0 && (
          <div className="w-6 h-6 bg-gray-100 rounded-full border-2 border-white flex items-center justify-center">
            <span className="text-xs font-medium text-gray-500">
              +{remaining}
            </span>
          </div>
        )}
      </div>
    </div>
  );
}; 